package com.zzh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzh.controller.utils.R;
import com.zzh.pojo.Captcha;
import com.zzh.service.CaptchaService;
import com.zzh.mapper.CaptchaMapper;


import com.zzh.ut.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
 *
 */
@Service
@Slf4j
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, Captcha>
        implements CaptchaService {
    @Autowired
    private CaptchaMapper captchaMapper;

    @Override
    public R addCode(Captcha captcha) {
        if (!MyUtils.isEmail(captcha.getEmail())){
            return R.error("请输入正确的邮箱!");
        }
        String code = MyUtils.getCode();
        LambdaQueryWrapper<Captcha> wrapper = new LambdaQueryWrapper<Captcha>();
        wrapper.eq(Captcha::getEmail,captcha.getEmail());
        Captcha dbCaptcha = captchaMapper.selectOne(wrapper);
        //没查到记录说明表中没存验证码
        if (dbCaptcha == null) {
            captcha.setCaptcha(code);
            log.info("邮箱:" + captcha.getEmail() + "的验证码是:" + code);
            int i = captchaMapper.insert(captcha);
            if (i > 0) {
                String info = "用户:" + captcha.getEmail() + ",您的验证码发送成功!";
                return R.info(info);
            }
        }
        //判断上次获取验证码是否超过5分钟
        boolean failure = MyUtils.getFailure(MyUtils.getDateMillisecond(dbCaptcha.getUpdateTime()));
        if (failure){
            log.info("邮箱:" + captcha.getEmail() + "上次的验证码还没有失效!");
            return R.error("上次的验证码还没有失效!");
        }
        //说明查到了记录,更新验证码
        dbCaptcha.setCaptcha(code);
        int i = captchaMapper.updateById(dbCaptcha);
        if (i > 0){
            log.info("邮箱:" + captcha.getEmail() + "的验证码是:" + code);
            String info = "用户:" + captcha.getEmail() + ",您的验证码发送成功!";
            return R.info(info);
        }
        return R.error();
    }
}




